import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/login/login.vue'
import layout from '@/views/layout/layout.vue'
import find from '@/views/layout/find/find.vue'
import my from '@/views/layout/my/my.vue'
import company from '@/views/layout/company/company.vue'
import doExercise from '@/views/layout/doExercise/doExercise.vue'
import info from '@/views/info/info.vue'
import editInfo from '@/views/info/editInfo.vue'
import avatar from '@/views/info/avatar.vue'
import shareList from '@/views/shareList/shareList.vue'
import shareDetail from '@/views/shareList/shareDetail.vue'
import search from '@/views/search/search.vue'
import interview from '@/views/layout/doExercise/interview.vue'
import { getuserInfo } from '@/api/login.js'
import { Toast } from 'vant'
import { getLocal } from '@/utils/local.js'
import store from '@/store/index.js'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: login
  },
  {
    path: '/layout',
    component: layout,
    children: [
      { path: '/find', component: find },
      { path: '/my', component: my, meta: { needLogin: true } },
      { path: '/company', component: company },
      { path: '/doExercise', component: doExercise, meta: { needLogin: true } }
    ]
  },
  {
    path: '/info',
    component: info,
    meta: {
      needLogin: true
    }
  },

  {
    path: '/editInfo',
    component: editInfo,
    meta: {
      needLogin: true
    }
  },
  {
    path: '/avatar',
    component: avatar,
    meta: {
      needLogin: true
    }
  },
  {
    path: '/shareList',
    component: shareList
  },
  {
    path: '/shareDetail/:id',
    component: shareDetail
  },
  {
    path: '/search',
    component: search
  },
  {
    path: '/interview',
    component: interview,
    meta: {
      needLogin: true
    }
  }
]

const router = new VueRouter({
  routes
})
// 设置路由前置守卫
router.beforeEach(async (to, from, next) => {
  const needLogin = to.meta.needLogin
  if (!needLogin) {
    next()
  } else {
    const token = getLocal('token')
    // console.log(token)
    if (token) {
      const userInfo = store.state.userInfo
      if (userInfo) {
        next()
      } else {
        const res = await getuserInfo()
        res.data.data.avatar = 'http://localhost:1337' + res.data.data.avatar
        store.commit('setUserInfo', res.data.data)
        // console.log('重新获取到的数据', store.state.userInfo)
        next()
      }
    } else {
      Toast.fail('请登录！')
      // 用来 ?_redirect=' + to.fullPath保存退出登录时所处的位置
      router.push('/login?_redirect=' + to.fullPath)
    }
    next()
  }
})

export default router
